//
//  TaxiSelectionView.m
//  NZTaxi
//
//  Created by Allan Vergara on 25/11/11.
//  Copyright (c) 2011 List-it. All rights reserved.
//

#import "TaxiSelectionView.h"
#import "MyManager.h"

@implementation TaxiSelectionView

@synthesize responseData, imageView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction)btnDoneClick:(id)sender
{
     MyManager *sharedManager = [MyManager sharedMyManager];	     
     
     if ([sharedManager.customerPickupAddress length] > 0 && [sharedManager.customerDestinationAddress length] > 0) {	
     
     NSString *bookingURL;
     
     if ([sharedManager.specialInstructions length] > 0) { 
         bookingURL = [NSString stringWithFormat:@"%@%@%@?deviceID=%@&customerName=%@&pickup=%@&destination=%@&mobileNo=%@&telNo=6789&specialInstruction=%@&traveDate=0&taxiCoy=1&vehicleType=0",
                       sharedManager.listItDomain, 
                       sharedManager.webServicePath, 
                       sharedManager.requestJobAPI,
                       sharedManager.deviceUDID,
                       sharedManager.customerName,
                       sharedManager.customerPickupAddress,
                       sharedManager.customerDestinationAddress,
                       sharedManager.customerMobileNo,
                       sharedManager.specialInstructions];
     }
     else {
         bookingURL = [NSString stringWithFormat:@"%@%@%@?deviceID=%@&customerName=%@&pickup=%@&destination=%@&mobileNo=%@&telNo=6789&traveDate=0&taxiCoy=1&vehicleType=0",
                       sharedManager.listItDomain, 
                       sharedManager.webServicePath, 
                       sharedManager.requestJobAPI,
                       sharedManager.deviceUDID,
                       sharedManager.customerName,
                       sharedManager.customerPickupAddress,
                       sharedManager.customerDestinationAddress,
                       sharedManager.customerMobileNo];
     }
         
         
         NSLog(@"%@", bookingURL);
         
         
         // perform request	
         NSURL *url = [NSURL URLWithString:[bookingURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
         NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
         NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];		
         
         // ADV removed temporary [self showActivityIndicator];
         // ADV removed temporary [self ResetFields];
         [connection release];
         [request release];
     } else {
         //NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"Please provide a pick up and destination address."
         //                                                     forKey:NSLocalizedDescriptionKey];
         //NSError *error = [NSError errorWithDomain:@"HTTP" code:0 userInfo:userInfo];
         // ADV removed temporary [self handleError:error];
     }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {	    
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    
    // http code within 200 range is ok
    if ((([httpResponse statusCode]/100) == 2)) {
        [responseData setLength:0];
        
        // inform customer that their job requires has been dispatched
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Booking sent successfully" 
                                                            message:@"Your taxi booking has been dispatched. You will get a text message once your request has been received by a designated taxi." 
                                                           delegate:nil 
                                                  cancelButtonTitle:@"OK" 
                                                  otherButtonTitles:nil];
        
        [alertView show];
        [alertView release];
        [self.navigationController popViewControllerAnimated:TRUE];
        
    } else {
        NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"Problem encountered while connecting to the server. Please try again."
                                                             forKey:NSLocalizedDescriptionKey];
        //NSError *error = [NSError errorWithDomain:@"HTTP" code:[httpResponse statusCode] userInfo:userInfo];
    }		
    
    //[self showBookItButton];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	if ([error code] == kCFURLErrorNotConnectedToInternet){
		NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"You have a problem with your internet connection. Please try again." 
															 forKey:NSLocalizedDescriptionKey ];
		
        //NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain
        //                                                 code:kCFURLErrorNotConnectedToInternet
        //                                             userInfo:userInfo];
		// ADV removed temporary [self handleError:noConnectionError];
	} else {
		// ADV removed temporary [self handleError:error];
	}
	
	// ADV removed temporary [self showBookItButton];
}

/*
 *	Expected JSON reply format : 
 *		{ "d" : { "RequestJob" : { "status":200, "message":"OK" } } }
 *
 *	TODO: check for empty status
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {		
	NSString *jsonStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	
	// assign the new string to a static string so we can release jsonString
	NSString *cleanStr = [jsonStr stringByReplacingOccurrencesOfString:@"\\" withString:@""];
	cleanStr = [cleanStr stringByReplacingOccurrencesOfString:@"\"{" withString:@"{"];
	cleanStr = [cleanStr stringByReplacingOccurrencesOfString:@"}\"" withString:@"}"];
	
	NSDictionary *dictionary = [cleanStr JSONValue];
	NSDictionary *cleanDictionary = (NSDictionary *)[dictionary objectForKey:@"d"];
	
	NSDictionary *result = (NSDictionary *)[cleanDictionary objectForKey:@"RequestJob"];
	
	NSInteger status = [[result objectForKey:@"status"] integerValue];
	
	switch (status) {
		case 500:
			// TODO: issue error message
			break;
		case 200:
			// TODO: populate history
			// ADV removed temporary [self showBookItButton];			
			break;
		default:
			break;
	}
    
    responseData = nil;
	[responseData release];
    [jsonStr release];
}

- (void)dealloc {
	[responseData release];
    [imageView release];
    
    [super dealloc];
}

@end
